package day2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import utility.JdbcUtils;


public class ResultSetMetaDataTest {
	public static void main(String[] args) throws SQLException {
		String sql = "select id, name as n from user where id < 5";
		List<Map<String, Object>> map=getResultMap(sql);
		System.out.println(map);
	}

	private static List<Map<String, Object>> getResultMap(String sql) throws SQLException {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
		try {
			// 2.建立连接
			con = JdbcUtils.getConnection();
			// 3.创建语句
			
			st = con.prepareStatement(sql);
			rs=st.executeQuery();
			ResultSetMetaData rsd=rs.getMetaData();
			int count=rsd.getColumnCount();
			List<String> columnNameList=new ArrayList<String>();
			for(int i=1;i<=count;i++){
				System.out.println(rsd.getColumnClassName(i));
				System.out.println(rsd.getColumnName(i));
				System.out.println(rsd.getColumnLabel(i));
				columnNameList.add(rsd.getColumnLabel(i));
			}
			
			while(rs.next()){
				Map<String, Object> map=new HashMap<String, Object>();
				for(String s:columnNameList){
					map.put(s, rs.getObject(s));
				}
				list.add(map);
			}
			return list;
		}finally{
			JdbcUtils.free(rs, st, con);
		}
	}
}
			
			
